package com.mutual.index.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.aliyuncs.exceptions.ClientException;
import com.google.common.collect.Maps;
import com.mutual.app.pojo.AppResult;
import com.mutual.appUserInfo.pojo.AppUserInfoProduct;
import com.mutual.appUserInfo.service.AppUserInfoProductService;
import com.mutual.appUserInfo.service.AppUserInfoService;
import com.mutual.attachment.service.AttachmentService;
import com.mutual.commom.service.RedisService;
import com.mutual.commom.util.DateUtil;
import com.mutual.commom.util.JSONUtil;
import com.mutual.commom.util.SMSUtil;
import com.mutual.commom.util.SystemUtil;
import com.mutual.commom.zfb.AlipayConfig;
import com.mutual.config.AndroidVersionEntity;
import com.mutual.config.BusinessEntity;
import com.mutual.config.IosVersionEntity;
import com.mutual.family.pojo.Family;
import com.mutual.family.service.FamilyService;
import com.mutual.healthInfo.pojo.HealthInfo;
import com.mutual.healthInfo.service.HealthInfoService;
import com.mutual.invite.service.InviteService;
import com.mutual.product.pojo.Product;
import com.mutual.product.service.ProductService;
import com.mutual.vipAnnualFee.pojo.VipAnnualFee;
import com.mutual.vipAnnualFee.service.VipAnnualFeeService;

/**
 * 主界面
 * 
 * @author asus
 *
 */
@Controller
@RequestMapping("/index")
public class IndexController {

	@Resource
	private AppUserInfoService appUserInfoService;

	@Resource
	private AppUserInfoProductService appUserInfoProductService;

	@Resource
	private FamilyService familyService;

	@Resource
	private InviteService inviteService;

	@Resource
	private ProductService productService;

	@Resource
	private AttachmentService attachmentService;

	@Resource
	private HealthInfoService healthInfoService;

	@Resource
	private VipAnnualFeeService vipAnnualFeeService;

	@Resource
	private RedisService redisService;
	
	@Resource
	private AndroidVersionEntity androidVersionEntity;
	
	@Resource
	private IosVersionEntity iosVersionEntity;
	
	@Resource
	private BusinessEntity businessEntity;

	private static final Logger log = LoggerFactory.getLogger(IndexController.class);

	/**
	 * 产品列表
	 * 
	 * @param appUserId
	 * @return
	 */
	@GetMapping("/selectProductList")
	@ResponseBody
	public AppResult selectProductList() {
		AppResult appResult = new AppResult();
		List<Product> productList = productService.selectProductList(Maps.newHashMap());
		appResult.setMsg(AppResult.MSG_SELECT_SUCCESS);
		appResult.setData(productList);
		log.info("产品列表返回：{}", JSONUtil.getJSONFromObj(appResult));
		return appResult;
	}

	/**
	 * 用户个数
	 * 
	 * @param appUserId
	 * @return
	 */
	@GetMapping("/selectAppUserCount")
	@ResponseBody
	public AppResult selectAppUserCount() {
		AppResult appResult = new AppResult();
		int count = appUserInfoService.selectAppUserInfoCount(Maps.newHashMap());
		appResult.setMsg(AppResult.MSG_SELECT_SUCCESS);
		appResult.setData(count+SystemUtil.getInt(businessEntity.getAppUserCount()));
		log.info("用户个数返回：{}", JSONUtil.getJSONFromObj(appResult));
		return appResult;
	}

	@GetMapping("/selectProductDetail")
	@ResponseBody
	public AppResult selectProductDetail(int id) {
		AppResult appResult = new AppResult();
		Product product = productService.selectByPrimaryKey(id);
		appResult.setMsg(AppResult.MSG_SELECT_SUCCESS);
		appResult.setData(product);
		log.info("产品详情返回：{}", JSONUtil.getJSONFromObj(appResult));
		return appResult;
	}

	@GetMapping("/selectFamilyList")
	@ResponseBody
	public AppResult selectFamilyList(Family family) {
		AppResult appResult = new AppResult();
		List<Family> familyList = familyService.selectFamilyList(family);
		appResult.setMsg(AppResult.MSG_SELECT_SUCCESS);
		appResult.setData(familyList);
		log.info("家庭列表返回：{}", JSONUtil.getJSONFromObj(appResult));
		return appResult;
	}

	/**
	 * 家庭成员详情
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/detailFamily")
	@ResponseBody
	public AppResult selectFamilyList(int id) {
		AppResult appResult = new AppResult();
		Family family = familyService.selectByPrimaryKey(id);
		appResult.setMsg(AppResult.MSG_SELECT_SUCCESS);
		appResult.setData(family);
		log.info("用户详情：{}", JSONUtil.getJSONFromObj(appResult));
		return appResult;
	}

	/**
	 * 检查家人的计划
	 * 
	 * @param family
	 * @return
	 */
	@PostMapping("/check_exist_order")
	@ResponseBody
	public AppResult check_exist_order_for_family(@RequestParam Map<String, Object> param) {
		AppResult appResult = new AppResult();
		int count = appUserInfoProductService.selectTotalCount(param);
		if (count > 0) {
			appResult.setStatus(AppResult.STATUS_FAILED);
			appResult.setMsg(SystemUtil.getInt(param.get("type")) == 1 ? "您已加入过该计划" : "该家人已加入过该计划");
			return appResult;
		}
		log.info("检查家人的计划：{}", JSONUtil.getJSONFromObj(appResult));
		return appResult;
	}

	/**
	 * 健康资讯列表
	 * 
	 * @param param
	 * @return
	 */
	@GetMapping("/selectHealthInfoList")
	@ResponseBody
	public AppResult selectHealthInfoList(@RequestParam Map<String, Object> param) {
		param.put("status", HealthInfo.STATUS_YES);
		AppResult appResult = new AppResult();
		List<HealthInfo> healthInfoList = healthInfoService.selectHealthInfoList(param);
		for (HealthInfo h : healthInfoList) {
			h.setUpdateDateStr(DateUtil.date2String(h.getUpdateDate(), DateUtil.pattern));
		}
		appResult.setMsg(AppResult.MSG_SELECT_SUCCESS);
		appResult.setData(healthInfoList);
		log.info("健康资讯列表返回：{}", JSONUtil.getJSONFromObj(appResult));
		return appResult;
	}

	/**
	 * 健康资讯详情
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/deatailHealthInfo")
	@ResponseBody
	public AppResult selectHealthInfoList(int id) {
		HealthInfo updateObj = new HealthInfo();
		updateObj.setId(id);
		updateObj.setClickCount(1);
		healthInfoService.updateByPrimaryKey(updateObj);
		AppResult appResult = new AppResult();
		appResult.setMsg(AppResult.MSG_SELECT_SUCCESS);
		HealthInfo healthInfo = healthInfoService.selectByPrimaryKey(id);
		healthInfo.setUpdateDateStr(DateUtil.date2String(healthInfo.getUpdateDate(), DateUtil.pattern));
		appResult.setData(healthInfo);
		log.info("健康资讯详情返回：{}", JSONUtil.getJSONFromObj(appResult));
		return appResult;
	}

	/**
	 * 年会费查询
	 * 
	 * @param vipAnnualFee
	 * @return
	 */
	@GetMapping("/selectVipAnnualFeeByIdCodeAndYear")
	@ResponseBody
	public AppResult selectVipAnnualFeeByIdCodeAndYear(VipAnnualFee vipAnnualFee) {
		AppResult appResult = new AppResult();
		appResult.setMsg(AppResult.MSG_SELECT_SUCCESS);
		appResult.setData(vipAnnualFeeService.getVipAnnuaFee(vipAnnualFee));
		log.info("年会费查询返回：{}", JSONUtil.getJSONFromObj(appResult));
		return appResult;
	}

	/**
	 * 年会费
	 * 
	 * @param vipAnnualFee
	 * @return
	 */
	@GetMapping("/selectVipAnnualFeeByIdCode")
	@ResponseBody
	public AppResult selectVipAnnualFeeByIdCode(VipAnnualFee vipAnnualFee) {
		AppResult appResult = new AppResult();
		appResult.setMsg(AppResult.MSG_SELECT_SUCCESS);
		VipAnnualFee vipAnnualFeeSelect = vipAnnualFeeService.selectVipAnnualFeeByIdCodeAndYear(vipAnnualFee);
		appResult.setData(vipAnnualFeeSelect);
		log.info("年会费查询返回：{}", JSONUtil.getJSONFromObj(appResult));
		return appResult;
	}

	/**
	 * 获取短信验证码
	 * 
	 * @param vipAnnualFee
	 * @return
	 */
	@PostMapping("/getSMSCode")
	@ResponseBody
	public AppResult getSMSCode(String mobile) {
		AppResult appResult = new AppResult();
		String result = null;
		try {
			result = SMSUtil.getSendSMSCode(mobile);
			if (SMSUtil.SENDCODE_ERROR.equals(result)) {
				appResult.setMsg("验证码发送失败，请稍后重试");
				appResult.setStatus(AppResult.STATUS_FAILED);
			} else {
				appResult.setData(result);
				redisService.saveRedisValueTime(mobile, result, 60 * 5);// 验证码5分钟失效
			}
			log.info("验证码获取返回：{}", JSONUtil.getJSONFromObj(appResult));
		} catch (ClientException e) {
			log.error("发送验证码出错:", e);
			appResult.setMsg("验证码发送出现异常，请稍后重试");
			appResult.setStatus(AppResult.STATUS_FAILED);
		}
		return appResult;
	}

	/**
	 * 校验短信验证码
	 * 
	 * @param vipAnnualFee
	 * @return
	 */
	@PostMapping("/checkSMSCode")
	@ResponseBody
	public AppResult checkSMSCode(String mobile, String code) {
		AppResult appResult = new AppResult();
		String result = redisService.getValueByRedisKey(mobile);
		if (StringUtils.isEmpty(result) || !code.equals(result)) {
			appResult.setStatus(AppResult.STATUS_FAILED);
			appResult.setMsg("验证码输入有误");
		} else {
			redisService.deleteRedisByKey(mobile);
		}
		return appResult;
	}
	
	/**
	 * 版本号查询
	 * @return
	 */
	@GetMapping("/selectVersion")
	@ResponseBody
	public AppResult selectVersion(String customerSource) {
		AppResult appResult = new AppResult();
		appResult.setData("ios".equals(customerSource)?iosVersionEntity:androidVersionEntity);
		log.info("版本号查询返回：{}", JSONUtil.getJSONFromObj(appResult));
		return appResult;
	}

	public static void main(String[] args) {
		// DateTimeFormatter format = DateTimeFormat .forPattern("yyyy-MM-dd
		// HH:mm:ss");
		// DateTime createTime = DateTime.parse("2017-10-09 16:35:16", format);
		// DateTime nextYear = createTime.plusYears(1);
		// Date nowDate = new Date();
		// if(nextYear.getMillis()<nowDate.getTime()) {
		// System.out.println(1);
		// }

		// DateTimeFormatter format = DateTimeFormat .forPattern("yyyy-MM-dd
		// HH:mm:ss");
		// DateTime createTime = DateTime.parse("2018-10-09 16:35:16", format);
		// DateTime nextDay = createTime.plusDays(1);
		// Date nowDate = new Date();
		// if(nextDay.getMillis()<nowDate.getTime()) {
		// System.out.println(1);
		// }

		Date vNow = new Date();
		String WIDout_trade_no = "";
		WIDout_trade_no += vNow.getYear();
		WIDout_trade_no += vNow.getMonth() + 1;
		WIDout_trade_no += vNow.getDate();
		WIDout_trade_no += vNow.getHours();
		WIDout_trade_no += vNow.getSeconds();
		WIDout_trade_no += vNow.getTime();
		System.out.println(WIDout_trade_no);
	}
}
